package com.yueya.basic.role.service;

import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yueya.basic.dept.model.Dept;
import com.yueya.basic.role.model.RoleUser;
import com.yueya.common.model.Tree;
import com.yueya.common.util.UUIDGenerator;

/**
 * 
 * @author zhujun 角色和用户关联表
 * 
 */
public class RoleUserService {

	/**
	 * 获取机构用户树
	 * @param id
	 * @return
	 */
	public List<Tree> getTreeRoleUser(String id) {
		List<Record> list = Db.find("SELECT * FROM t_role_user WHERE role_id=?", id);
		List<Tree> rt = Dept.dao.toTreeList(Dept.dao._r(), "", "");
		List<Tree> rl = Dept.dao.toTreeList2(Dept.dao._rtl());
		List<Tree> ret = Dept.dao.splitTreeU(rt, rl, rl, list);
		parseUserTree(ret, list);
		return ret;
	}

	private void parseUserTree(List<Tree> list, List<Record> checkedList) {
		for (Tree temp : list) {
			for (Record t : checkedList) {
				if (t.get("user_id").equals(temp.getId()))
					temp.setChecked(true);
			}
			if (temp.getChildren() != null)
				parseUserTree(temp.getChildren(), checkedList);
		}
	}

	/**
	 * 先删除userid关联的角色，再添加
	 * 
	 * @param userid
	 * @param roleids
	 * @return
	 */
	@Before(Tx.class)
	public boolean saveUserRoles(String userid, String[] roleids) {
		RoleUser ru = null;
		// 删除
		RoleUser.dao.deleteByUserId(userid);

		boolean bl = false;
		if (roleids != null && roleids.length > 0) {
			for (int i = 0; i < roleids.length; i++) {
				ru = new RoleUser();
				ru.set("id", UUIDGenerator.getUUID());
				ru.set("user_id", userid);
				ru.set("role_id", roleids[i]);
				bl = ru.save();
			}
		}
		return bl;
	}

	/**
	 * 先删除roleid关联的用户，再添加
	 * 
	 * @param roleid
	 * @param userids
	 * @return
	 */
	@Before(Tx.class)
	public boolean saveRoleUsers(String roleid, String[] userids) {
		RoleUser ru = null;
		// 删除
		RoleUser.dao.deleteByRoleId(roleid);

		boolean bl = false;
		if (userids != null && userids.length > 0) {
			for (int i = 0; i < userids.length; i++) {
				ru = new RoleUser();
				ru.set("id", UUIDGenerator.getUUID());
				ru.set("user_id", userids[i]);
				ru.set("role_id", roleid);
				bl = ru.save();
			}
		}
		return bl;

	}

}
